use iced::{Element, Length, Color};
use iced::widget::{text_input, button, text, column, row, container, scrollable};
use crate::theme::CdbTheme;
use cdb_ai::{AiEngine, GeneratedSql};

/// AI助手组件消息
#[derive(Debug, Clone)]
pub enum AiAssistantMessage {
    /// 输入自然语言查询
    InputChanged(String),
    /// 生成SQL
    GenerateSql,
    /// 清空输入
    ClearInput,
    /// 应用生成的SQL
    ApplySql(String),
    /// AI响应接收
    SqlGenerated(Result<GeneratedSql, String>),
}

/// AI助手组件
#[derive(Debug)]
pub struct AiAssistant {
    /// 当前输入的自然语言查询
    input: String,
    /// 生成的SQL历史
    generated_queries: Vec<GeneratedSql>,
    /// 是否正在生成
    is_generating: bool,
    /// 错误信息
    error_message: Option<String>,
}

impl AiAssistant {
    /// 创建新的AI助手
    pub fn new() -> Self {
        Self {
            input: String::new(),
            generated_queries: Vec::new(),
            is_generating: false,
            error_message: None,
        }
    }
    
    /// 更新组件状态
    pub fn update(&mut self, message: AiAssistantMessage) -> Option<String> {
        match message {
            AiAssistantMessage::InputChanged(input) => {
                self.input = input;
                self.error_message = None;
                None
            }
            AiAssistantMessage::GenerateSql => {
                if !self.input.trim().is_empty() {
                    self.is_generating = true;
                    self.error_message = None;
                    // 返回输入内容，让调用者处理AI生成
                    Some(self.input.clone())
                } else {
                    self.error_message = Some("请输入自然语言查询".to_string());
                    None
                }
            }
            AiAssistantMessage::ClearInput => {
                self.input.clear();
                self.error_message = None;
                None
            }
            AiAssistantMessage::ApplySql(sql) => {
                // 返回SQL让调用者应用到编辑器
                Some(sql)
            }
            AiAssistantMessage::SqlGenerated(result) => {
                self.is_generating = false;
                match result {
                    Ok(generated_sql) => {
                        self.generated_queries.insert(0, generated_sql);
                        // 限制历史记录数量
                        if self.generated_queries.len() > 10 {
                            self.generated_queries.truncate(10);
                        }
                        self.error_message = None;
                    }
                    Err(error) => {
                        self.error_message = Some(error);
                    }
                }
                None
            }
        }
    }
    
    /// 渲染AI助手界面
    pub fn view<'a>(&'a self, theme: &CdbTheme) -> Element<'a, AiAssistantMessage> {
        let title = text("AI SQL助手")
            .size(16)
            .color(theme.colors.foreground);
        
        // 输入区域
        let input_field = text_input("输入自然语言查询，例如：查找所有用户", &self.input)
            .on_input(AiAssistantMessage::InputChanged)
            .padding(8)
            .size(14);
        
        // 按钮行
        let generate_button = button(
            text(if self.is_generating { "生成中..." } else { "生成SQL" })
                .size(12)
                .color(Color::WHITE)
        )
        .on_press_maybe(if self.is_generating { None } else { Some(AiAssistantMessage::GenerateSql) })
        .style(move |theme: &iced::Theme, status| {
            button::Style {
                background: Some(Color::from_rgb(0.2, 0.6, 0.2).into()),
                text_color: Color::WHITE,
                border: iced::Border::default(),
                shadow: iced::Shadow::default(),
            }
        })
        .padding([6, 12]);
        
        let clear_button = button(
            text("清空")
                .size(12)
                .color(Color::WHITE)
        )
        .on_press(AiAssistantMessage::ClearInput)
        .style(move |theme: &iced::Theme, status| {
            button::Style {
                background: Some(Color::from_rgb(0.6, 0.2, 0.2).into()),
                text_color: Color::WHITE,
                border: iced::Border::default(),
                shadow: iced::Shadow::default(),
            }
        })
        .padding([6, 12]);
        
        let button_row = row![generate_button, clear_button]
            .spacing(10);
        
        // 错误信息
        let error_section = if let Some(error) = &self.error_message {
            Some(text(error)
                .size(12)
                .color(Color::from_rgb(0.8, 0.2, 0.2)))
        } else {
            None
        };
        
        // 生成的SQL历史
        let history_title = text("生成历史")
            .size(14)
            .color(theme.colors.foreground);
        
        let mut history_items = column![];
        
        for (index, generated) in self.generated_queries.iter().enumerate() {
            let confidence_color = if generated.confidence > 0.8 {
                Color::from_rgb(0.2, 0.8, 0.2)
            } else if generated.confidence > 0.6 {
                Color::from_rgb(0.8, 0.8, 0.2)
            } else {
                Color::from_rgb(0.8, 0.2, 0.2)
            };
            
            let sql_text = text(&generated.sql)
                .size(12)
                .color(theme.colors.foreground);
            
            let confidence_text = text(format!("置信度: {:.1}%", generated.confidence * 100.0))
                .size(10)
                .color(confidence_color);
            
            let explanation_text = text(&generated.explanation)
                .size(10)
                .color(theme.colors.muted_foreground);
            
            let apply_button = button(
                text("应用")
                    .size(10)
                    .color(Color::WHITE)
            )
            .on_press(AiAssistantMessage::ApplySql(generated.sql.clone()))
            .style(move |theme: &iced::Theme, status| {
                button::Style {
                    background: Some(Color::from_rgb(0.2, 0.4, 0.8).into()),
                    text_color: Color::WHITE,
                    border: iced::Border::default(),
                    shadow: iced::Shadow::default(),
                }
            })
            .padding([4, 8]);
            
            // 警告信息
            let warnings = if !generated.warnings.is_empty() {
                let warning_text = generated.warnings.join("; ");
                Some(text(format!("⚠️ {}", warning_text))
                    .size(10)
                    .color(Color::from_rgb(0.8, 0.6, 0.2)))
            } else {
                None
            };
            
            let mut item_column = column![
                sql_text,
                row![confidence_text, apply_button].spacing(10),
                explanation_text,
            ].spacing(5);
            
            if let Some(warning) = warnings {
                item_column = item_column.push(warning);
            }
            
            let item_container = container(item_column)
                .style(move |theme: &iced::Theme| {
                    container::Style {
                        background: Some(Color::from_rgb(0.05, 0.05, 0.05).into()),
                        border: iced::Border {
                            color: Color::from_rgb(0.2, 0.2, 0.2),
                            width: 1.0,
                            radius: 4.0.into(),
                        },
                        text_color: None,
                        shadow: iced::Shadow::default(),
                    }
                })
                .padding(10)
                .width(Length::Fill);
            
            history_items = history_items.push(item_container);
            
            if index < self.generated_queries.len() - 1 {
                history_items = history_items.push(
                    container(text(""))
                        .height(5)
                );
            }
        }
        
        let history_scroll = scrollable(history_items)
            .width(Length::Fill)
            .height(Length::Fill);
        
        // 组装完整界面
        let mut content = column![
            title,
            input_field,
            button_row,
        ].spacing(10);
        
        if let Some(error) = error_section {
            content = content.push(error);
        }
        
        content = content.push(history_title);
        content = content.push(history_scroll);
        
        container(content)
            .padding(15)
            .width(Length::Fill)
            .height(Length::Fill)
            .into()
    }
    
    /// 获取当前输入
    pub fn current_input(&self) -> &str {
        &self.input
    }
    
    /// 是否正在生成
    pub fn is_generating(&self) -> bool {
        self.is_generating
    }
    
    /// 获取生成历史
    pub fn generated_queries(&self) -> &[GeneratedSql] {
        &self.generated_queries
    }
}

impl Default for AiAssistant {
    fn default() -> Self {
        Self::new()
    }
}
